import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

// 按需引入
// import AutoImport from 'unplugin-auto-import/vite'
// import Components from 'unplugin-vue-components/vite'
// import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// 手动引入组件时候，自动加载elementui样式
import ElementPlus from 'unplugin-element-plus/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// https://vitejs.dev/config/
export default ({ mode }) => {
  const myEnv = loadEnv(mode, process.cwd());
  // console.log(myEnv, 'myEnv')
  return defineConfig({
    plugins: [
      vue(),
      vueJsx(),
      // 按需引入
      // AutoImport({
      //   resolvers: [ElementPlusResolver()],
      // }),
      // Components({
      //   resolvers: [ElementPlusResolver()],
      // }),
      ElementPlus(),

      // 查看readme相关文章
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), './src/components/svgIcon/icon')],
        symbolId: 'icon-[name]', // 控制symbolId的格式
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@u': fileURLToPath(new URL('./src/utils', import.meta.url)),
        '@a': fileURLToPath(new URL('./src/api', import.meta.url)),
        '@c': fileURLToPath(new URL('./src/component', import.meta.url)),
        '@s': fileURLToPath(new URL('./src/styles', import.meta.url)),
      }
    },
    // scss全局变量等
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
          additionalData: `@use "@/styles/main.scss" as *;`
        },
      }
    },
    server: {
      // port: 8080,// 访问端口
      proxy: {
        [myEnv.VITE_APP_API]: {
          target: myEnv.VITE_API_DEV_TARGET,
          changeOrigin: true,// 是否运行跨域
          ws: false,//wss连接
          secure: false,// https连接
          rewrite: (path) => {
            const regex = new RegExp(`^${myEnv.VITE_APP_API}`);
            // console.log(path, 'path', path.replace(regex, ''));
            // let str = path.replace(regex, '');
            // console.log(str, 'str')
            return path.replace(regex, '');
          },
        }
      }
    }
  })
}
